<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!--方案数据-->
      <el-form class="formBox searchForm" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
        label-width="60px">
        <el-form-item label="医院" prop="hospital" clearable>
          <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="200px" ref="department">
          </department>
        </el-form-item>
        <el-form-item label="适用专病" prop="diseaseId" clearable>
          <el-select v-model="queryParams.diseaseId" placeholder="请选择专病名称" clearable filterable style="width: 200px">
            <el-option v-for="(item, index) in classifyList" :key="index" :label="item.diseaseClassifyName"
              :value="item.diseaseClassifyId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称" prop="setMealName">
          <el-input v-model="queryParams.setMealName" placeholder="请输入套餐名称" clearable style="width: 200px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status" clearable>
          <el-select v-model="queryParams.status" placeholder="状态" clearable filterable style="width: 200px">
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange" style="width:240px" value-format="yyyy-MM-dd" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddMeal"
              v-hasPermi="['plan:package:add']">新增</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="getMealList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="mealList" @selection-change="handleSelectionChange" border :height="statisticalTableH"  ref="table">
          <el-table-column sortable label="方案编号" align="center" prop="setMealId" width="100" />
          <el-table-column label="医院" align="center" prop="hospitalName" width="150">
            <template slot-scope="scope">
              <departTag :options="deptNameLists" :value="scope.row.hospitalId" />
            </template>
          </el-table-column>
          <el-table-column label="科室" align="center" prop="deptName" width="150">
            <template slot-scope="scope">
              <departTag :options="deptNameLists" :value="scope.row.deptId" />
            </template>
          </el-table-column>
          <el-table-column sortable label="适用专病" align="center" prop="diseaseNames" :show-overflow-tooltip="true"
            width="150" />
          <el-table-column sortable label="套餐名称" align="center" prop="setMealName" :show-overflow-tooltip="true"
            width="150" />
          <el-table-column sortable label="套餐总价" align="center" prop="total" :show-overflow-tooltip="true" width="100">

            <template slot-scope="scope">
              <span>{{ Number(scope.row.total).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column sortable label="状态" align="center" width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column sortable label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['plan:package:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['plan:package:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-user" @click="goDetail(scope.row)"
                v-hasPermi="['plan:package:detail']">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getMealList" />
      </div>

    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="mealTitle" :visible.sync="mealOpen" width="670px" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="mealForm" :model="mealForm" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="套餐名称" prop="setMealName">
          <el-input v-model="mealForm.setMealName" placeholder="请输入套餐名称" style="width: 540px"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="使用科室" prop="deptId" v-if="mealOpen">
              <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="mealForm.hospitalId" :Optiohospitals="true"
                :deptIds="mealForm.deptId" :isdisabled="false" deptWidth="540px"></department>
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="适用专病" prop="diseaseIds">
          <el-select v-model="mealForm.diseaseIds" multiple clearable filterable placeholder="请选择适用专病"
            style="width: 540px">
            <el-option v-for="item in classifyList" :key="item.diseaseClassifyId" :label="item.diseaseClassifyName"
              :value="item.diseaseClassifyId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="mealForm.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否用于色斑平台" label-width="140px">
          <el-radio-group v-model="mealForm.platformType">
            <el-radio v-for="dict in stainArr" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="mealForm.remark" type="textarea" placeholder="请输入备注" style="width: 540px"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitMealForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="mealDetailTitle" :visible.sync="mealDetailVisible" :before-close="handleCloseMealDetail"
      width="85%" :close-on-click-modal="false" v-dialogDrag>
      <el-form class="formBox" :model="mealDetailParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="项目类别" prop="planCategoryId" clearable>
          <el-select v-model="mealDetailParams.planCategoryId" @change="changeList" filterable placeholder="请选择方案大类"
            clearable style="width: 220px">
            <el-option v-for="dict in dict.type.sys_plan_category" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方案名称" prop="planId">
          <el-select v-model="mealDetailParams.planId" placeholder="请选择专病名称" clearable filterable style="width: 420px">
            <el-option v-for="(item, index) in planList" :key="index" :label="item.medicalEquipment"
              :value="item.planId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="joinMeal">加入</el-button>
        </el-form-item>
      </el-form>

      <div class="formBox">
        <el-table v-loading="mealDetailLoading" :data="sysSetMealPlanList" border>
          <!--          <el-table-column label="方案编号" align="center" prop="sPlanId"  />-->
          <el-table-column label="项目类别" align="center" prop="planCategoryId" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ matchDict("sys_plan_category", scope.row.planCategoryId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="方案名称" align="center" prop="medicalEquipment" :show-overflow-tooltip="true"
            width="220" />
          <!--          <el-table-column label="用法" align="center" prop="usageId" :show-overflow-tooltip="true">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ matchDict("sys_plan_usage", scope.row.usageId) }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="用量及单位" align="center" prop="dosage" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.dosage ? scope.row.dosage + matchDict("sys_dosage_unit", scope.row.dosageUnit) : ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="频次" align="center" prop="frequencyId" :show-overflow-tooltip="true" width="160">
            <template slot-scope="scope">
              <!--              <span>{{ matchDict("sys_dosage_frequency", scope.row.frequencyId) }}</span>-->
              <el-select v-model="scope.row.frequencyId" clearable filterable placeholder="请选择频次" style="width: 120px">
                <el-option v-for="dict in dict.type.sys_dosage_frequency" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="默认数量" align="center" prop="num" :show-overflow-tooltip="true" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.num" :min="0" style="width: 120px" type="number"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="单价" align="center" prop="price" :show-overflow-tooltip="true" width="160">
            <!-- <template slot-scope="scope">
              <el-input v-model="scope.row.price" style="width: 120px" type="number"></el-input>
            </template> -->
          </el-table-column>
          <!-- <el-table-column label="优惠率" align="center" prop="discount" width="160">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.discount" size="mini" :precision="2" :step="0.01" :min="0"
                :max="1"></el-input-number></template>
          </el-table-column> -->
          <!-- <el-table-column label="先敷药" align="center" prop="isApplication" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.isApplication == 0 ? '是' : (scope.row.isApplication == 1 ? '否' : '') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="治疗仪器" align="center" prop="instruments" :show-overflow-tooltip="true" width="160" />
          <el-table-column label="治疗参数" align="center" prop="parameters" :show-overflow-tooltip="true" width="160" /> -->
          <el-table-column label="领取地点" align="center" prop="pickingLocation" width="202">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_picking_location" :value="scope.row.sex" />
              <!-- <el-select v-model="scope.row.pickingLocation" clearable filterable placeholder="领取地点" style="width: 180px">
                <el-option v-for="dict in dict.type.sys_picking_location" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select> -->
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" size="mini" style="width: 120px"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">

            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit"
                @click="handleUpdateMealDetail(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete"
                @click="handleDeleteMealDetail(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>


      </div>

    </el-dialog>



  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  changePlanStatus,
  addMeal,
  listMeal,
  delMeal,
  updateMeal,
  getMeal,
  changeMealStatus,
  addSysSetMeaplan,
  delSysSetMeaplan, updateSysSetMeaplan,
} from "@/api/system/plan";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listClassify } from "@/api/system/classify";
import department from "@/views/components/department/index.vue";
import departTag from "@/views/components/department/departTag.vue";
import { deptNameList } from "@/api/system/dept";
export default {
  name: "single",
  components: { department, departTag },
  dicts: [
    "sys_normal_disable",
    "sys_manage_diseases",
    "sys_plan_category",
    "sys_dosage_unit",
    "sys_treatment_parameter",
    "sys_dosage_frequency",
    "sys_plan_usage",
    "sys_yes_no",
    "sys_picking_location",
  ],
  data() {
    return {
      statisticalTableH:undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 方案表格数据
      mealList: null,
      // 弹出层标题
      mealTitle: "",
      // 是否显示弹出层
      mealOpen: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      mealForm: {
        hospitalId: undefined,
        deptId: undefined,
        platformType:0
      },
      // 专病管理列表
      classifyList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        diseaseId: undefined,
        setMealName: undefined,
        status: undefined,
        hospitalId: undefined,
        deptId: undefined,
      },
      // 表单校验
      rules: {
        setMealName: [
          {
            required: true,
            message: "套餐名称不能为空",
            trigger: "blur",
          },
        ],
        diseaseIds: [
          {
            required: true,
            message: "适用专病不能为空",
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: "科室必选",
            trigger: "blur",
          },
        ],
      },
      deptNameLists: [],
      // 套餐详情
      mealDetailVisible: false,
      mealDetailTitle: '',
      // 查询参数
      mealDetailParams: {
        pageNum: 1,
        pageSize: 10,
        planId: undefined,
        planCategoryId: undefined,
        status: "0",
      },
      // 方案单项表格数据
      planList: null,
      joinSetMealId: '',
      sysSetMealPlanList: null,
      mealDetailLoading: false,
      stainArr: [{ value: 0, label: '否' }, { value: 1, label: '是' },],
    };
  },
  watch: {
    showSearch() {
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)
    }
  },
  created() {

    this.getClassifyList()
  },
  mounted() {
   this.changeHeight()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  computed: {},
  methods: {
    changeHeight() {
      if (this.$refs.statisticalTable) {
        const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
        let h = statisticalTableObj.top + 100
        this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
      } else {
        this.statisticalTableH = '500px'
      }
    },
    refreshData(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.hospitalId = data.hospitalId
      this.queryParams.deptId = data.deptId
      this.getdeptNameList();
    },
    changedepatData(data) {
      console.log("kaisshi")
      console.log(data)
      if (data && data.length > 0) {
        this.mealForm.deptId = data[0].deptId
        this.mealForm.hospitalId = data[0].parentId==100?data[0].deptId:data[0].parentId
      }else{
        this.mealForm.deptId = undefined
        this.mealForm.hospitalId = undefined
      }
    },
    // 回显医院及门诊
    getdeptNameList() {
      deptNameList().then((response) => {
        this.deptNameLists = response.data;
        this.getMealList();
      });
    },
    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },
    /** 查询方案列表 */
    getMealList() {
      this.loading = true;
      listMeal(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.mealList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询专病列表 */
    getClassifyList() {
      listClassify(
        this.addDateRange({
          pageNum: 1,
          pageSize: 9999,
          status: '0',
        })
      ).then((response) => {
        this.classifyList = response.rows;

      });
    },
    // 方案状态修改
    handleStatusChange(row) {
      console.log(row)
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm(
          "确认要" +
          text +
          "套餐名称为'" +
          row.setMealName +
          "'方案吗？"
        )
        .then(function () {
          return changeMealStatus(row.setMealId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.mealOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.mealForm = {
        diseaseIds: [],
        remark: undefined,
        setMealId: undefined,
        setMealName: undefined,
        status: "0",
        hospitalId: undefined,
        deptId: undefined,
        platformType:0
      };
      this.resetForm("mealForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getMealList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      if (this.$refs.department) {
        this.$refs.department.reset()
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.setMealId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAddMeal() {
      this.reset();
      this.mealOpen = true;
      this.mealTitle = "新增方案套餐";
      this.getClassifyList()

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('handleUpdate', row)
      this.reset();
      this.getClassifyList()
      const setMealId = row.setMealId || this.ids;
      getMeal(setMealId).then((response) => {
        let data =response.data;
        this.mealForm = response.data;
        if(data.platformType==undefined||data.platformType==null||data.platformType==''){
          this.mealForm.platformType=0
        }
        this.mealOpen = true;
        this.mealTitle = "修改方案套餐";
      });
    },

    /** 提交按钮 */
    submitMealForm: function () {
      console.log(this.mealForm)
      this.$refs["mealForm"].validate((valid) => {
        if (valid) {
          if (this.mealForm.setMealId != undefined) {
            updateMeal(this.mealForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.mealOpen = false;
              this.getMealList();
            });
          } else {
            addMeal(this.mealForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.mealOpen = false;
              this.getMealList();
              this.mealForm = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const setMealIds = row.setMealId || this.ids;
      this.$modal
        .confirm('是否确认删除方案编号为"' + setMealIds + '"的数据项？')
        .then(function () {
          return delMeal(setMealIds);
        })
        .then(() => {
          this.getMealList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // 套餐详情
    goDetail(row) {
      this.mealDetailVisible = true
      this.mealDetailTitle = row.setMealName + '设置'
      this.joinSetMealId = row.setMealId
      this.getSysSetMealPlanList()
      this.getList()

    },
    getSysSetMealPlanList() {
      this.mealDetailLoading = true
      getMeal(this.joinSetMealId).then(
        (response) => {
          this.sysSetMealPlanList = response.data.sysSetMealPlanList
          this.mealDetailLoading = false
        }

      )
    },
    changeList() {
      this.planList = []
      this.mealDetailParams.planId = ''
      this.getList()
    },
    /** 查询方案列表 */
    getList() {
      this.mealDetailParams.pageSize = 9999,
        listPlan(this.mealDetailParams).then(
          (response) => {
            this.planList = response.rows;
            // console.log('getList',this.planList)
          }
        );
    },
    handleCloseMealDetail() {
      this.mealDetailVisible = false
      this.getMealList();
    },
    joinMeal() {
      // if (this.mealDetailParams.planCategoryId && this.mealDetailParams.planId) {
      if ( this.mealDetailParams.planId) {
        // let mealItem=''
        // mealItem=this.planList.find(item=>{
        //   return item.planId==this.mealDetailParams.planId
        // })
        // mealItem.setMealId=this.joinSetMealId
        if (!!this.sysSetMealPlanList.find(item => item.planId == this.mealDetailParams.planId)) {
          this.$message.warning('请勿重复添加此单项')
        } else {
          addSysSetMeaplan(this.mealDetailParams.planId, this.joinSetMealId).then(
            (response) => {
              this.getSysSetMealPlanList()
              this.mealDetailParams.planId = ''
            }
          )
        }
      } else {
        this.$modal.msgWarning("请选择项目类别和方案名称");
      }
    },
    handleUpdateMealDetail(row) {
      console.log('handleUpdateMealDetail', row)
      if (row.frequencyId == '') {
        // this.$modal.msgError('请选择频次');
        this.$confirm('请选择频次！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            // console.log(content)
          })
          .catch((error) => {
            // console.log(error)
          })
      } else {
        updateSysSetMeaplan(row).then(
          (response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.getSysSetMealPlanList();
            } else {
              this.$modal.msgError(response.msg);
            }
          });
      }


    },
    handleDeleteMealDetail(row) {
      const sPlanId = row.sPlanId;
      const medicalEquipment = row.medicalEquipment;
      this.$modal
        .confirm('是否确认方案名称为"' + medicalEquipment + '"的数据项？')
        .then(function () {
          return delSysSetMeaplan(sPlanId);
        })
        .then(() => {
          this.getSysSetMealPlanList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },




  },
};
</script>
<style scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type="number"] {
  -moz-appearance: textfield;
}
</style>
